package com.ah.suams.controller;

import com.ah.suams.bean.Admin;
import com.ah.suams.dto.LoginToken;
import com.ah.suams.service.AdminService;
import com.ah.suams.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@SessionAttributes({"admin"})
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response, String id, String password, String code, String autoLogin){
        ModelAndView modelAndView = new ModelAndView();
        String vcode = (String)request.getSession().getAttribute("vcode");
        Admin admin = null;

        if(!vcode.equals(code)){
            //验证码不正确
            modelAndView.addObject("message","验证码错误！");
            modelAndView.setViewName("login");
        }else{
            admin = adminService.admin(id);
            if(admin != null && admin.getPassword().equals(password)){
                modelAndView.addObject("admin",admin);
                modelAndView.setViewName("index");
            }else{
                modelAndView.addObject("message","账号或密码错误！");
                modelAndView.setViewName("login");
            }
        }

        //自动登录
        if(admin!=null && autoLogin!=null && "1".equals(autoLogin)){
            //获取token
            LoginToken loginToken = TokenUtil.getLoginToken(request,admin);
            String token = loginToken.getToken();

            Cookie autoLoginCookie = new Cookie("autoLoginCookie",token);
            autoLoginCookie.setPath("/");
            //有效时间为48小时
            autoLoginCookie.setMaxAge(60*60*48);

            response.addCookie(autoLoginCookie);

            //服务器存储token
            ServletContext application = request.getServletContext();
            Map<String,LoginToken> loginTokenMap = (HashMap<String,LoginToken>)application.getAttribute("loginTokenMap");
            if(loginTokenMap == null){
                loginTokenMap = new HashMap<>();
                application.setAttribute("loginTokenMap",loginTokenMap);
            }
            loginTokenMap.put(token,loginToken);
        }

        return modelAndView;
    }


}
